import { computed, onUnmounted, ref } from 'vue'
import dayjs from 'dayjs'

/**
 * 倒计时组合函数
 */
export function useCountDown() {
  let timer
  // 响应式数据
  const time = ref(0)

  // 格式化时间
  const formattedTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))

  // 开启倒计时函数
  const startCountDown = (currentTime) => {
    time.value = currentTime
    // 每隔 1s 减1
    timer = setInterval(() => {
      if (time.value > 0) {
        time.value--
      }
    }, 1000)
  }

  // 组件销毁时清除定时器
  onUnmounted(() => {
    timer && clearInterval(timer)
  })

  return {
    formattedTime,
    startCountDown
  }
}
